package com.atguigu.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.auth.feign.MemberFeignService;
import com.atguigu.common.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author polaris
 * @date 2021/1/20 6:10 下午
 */

@Slf4j
@Controller
public class OauthController {

  @Resource
  private MemberFeignService memberFeignService;

  @Value("${oauth.weibo.client-id}")
  private String clientId;
  @Value("${oauth.weibo.client-secret}")
  private String clientSecret;
  @Value("${oauth.weibo.grant-type}")
  private String grantType;
  @Value("${oauth.weibo.redirect-uri}")
  private String redirectUri;
  @Value("${oauth.weibo.host}")
  private String host;
  @Value("${oauth.weibo.path}")
  private String path;

  @GetMapping("/oauth2.0/weibo/success")
  public String authorize(@RequestParam("code") String code, HttpSession session, HttpServletResponse servletResponse) throws Exception {
    //1. 使用code换取token，换取成功则继续2，否则重定向至登录页
    Map<String, String> query = new HashMap<>();
    query.put("client_id", clientId);
    query.put("client_secret", clientSecret);
    query.put("grant_type", grantType);
    query.put("redirect_uri", redirectUri);
    query.put("code", code);
    //发送post请求换取token
    HttpResponse response = HttpUtils.doPost(host, path, "post", new HashMap<String, String>(), query, new HashMap<String, String>());
    log.info("response,{}",response);
    Map<String,String> errors = new HashMap<>();
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
      //2. 调用member远程接口进行oauth登录，登录成功则转发至首页并携带返回用户信息，否则转发至登录页
      String json = EntityUtils.toString(response.getEntity());
      SocialUser socialUser = JSON.parseObject(json, new TypeReference<SocialUser>() {
      });
      log.info("socialUser,{}",socialUser);
      R login = memberFeignService.oauthlogin(socialUser);
      log.info("login,{}",login);
      //2.1 远程调用成功，返回首页并携带用户信息
      if (login.getCode() == 0) {
        String jsonString = JSON.toJSONString(login.getData());
        log.debug("----------------" + jsonString);
        MemberResponseVo memberResponseVo = JSON.parseObject(jsonString, new TypeReference<MemberResponseVo>() {
        });
        log.info("memberResponseVo,{}",memberResponseVo);
        log.debug("----------------" + memberResponseVo);
        MemberResponseVo vo = (MemberResponseVo) login.getData(new TypeReference<MemberResponseVo>() {
        });
        log.info("vo,{}",vo);
        session.setAttribute(AuthServerConstant.LOGIN_USER, vo);
        log.info("登陆成功");
        return "redirect:http://gulimall.com";
      } else {
        log.error("远程调用失败");
        //2.2 否则返回登录页
        errors.put("msg", "登录失败，请重试");
        session.setAttribute("errors", errors);
        return "redirect:http://auth.gulimall.com/login.html";
      }
    } else {
      log.info("失败，重定向回login");
      //失败，重定向回login
      errors.put("msg", "获得第三方授权失败，请重试");
      session.setAttribute("errors", errors);
      return "redirect:http://auth.gulimall.com/login.html";
    }
  }
}
